package com.dliyun.platform.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Locale;

@Slf4j
public class AesSecurityHex {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    public static void main(String[] args) throws Exception {
        System.out.println(generateDesKey(128));
    }

    public static String generateDesKey(int length) throws Exception {
        //实例化
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        //设置密钥长度
        kgen.init(length);
        //生成密钥
        SecretKey skey = kgen.generateKey();
        //返回密钥的二进制编码
        return hexEncode(skey.getEncoded());
    }


    /**
     * 加密
     *
     * @param input 加密的字符串
     * @param key   解密的key ,十六进制表示
     * @return HexString
     */

    public static String encrypt(String input, String key) {

        try {
            byte[] decodeKey = hexDecode(key);

            SecretKeySpec skey = new SecretKeySpec(decodeKey, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            byte[] crypted = cipher.doFinal(input.getBytes());

            return parseByte2HexStr(crypted);
        } catch (Exception e) {
            log.error("encrypt error", e);
            return "";
        }

    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;

    }

    /**
     * 解密
     *
     * @param input 解密的字符串
     * @param key   解密的key
     * @return String
     */
    public static String decrypt(String input, String key) {
        try {
            byte[] decodeKey = hexDecode(key);
            SecretKeySpec skey = new SecretKeySpec(decodeKey, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, skey);
            byte[] output = cipher.doFinal(parseHexStr2Byte(input));

            return new String(output);
        } catch (Exception e) {
            log.error("decrypt error", e);
            return "";
        }
    }


    /**
     * 将字节数组进行HEX编码.
     *
     * @param data 待编码的字节数组
     * @return 编码后的HEX字符串
     */
    private static String hexEncode(byte[] data) {

        StringBuilder sb = new StringBuilder();
        String stmp;
        for (byte datum : data) {
            stmp = (Integer.toHexString(datum & 0xFF));
            if (stmp.length() == 1)
                sb.append("0");
            sb.append(stmp);
        }
        return sb.toString().toUpperCase(Locale.CHINA);
    }

    /**
     * 将HEX编码的字符串转换为字节数组.
     *
     * @param data 待转换的HEX字符串
     * @return 转换后的字节数组
     */
    private static byte[] hexDecode(String data) {

        int n = data.length();
        if (n % 2 != 0) {
            data = "0" + data;
            n++;
        }
        n = (n / 2);
        byte[] bytes = new byte[n];
        for (int i = 0; i < n; i++) {
            bytes[i] = (byte) Integer.parseInt(data.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }
}
